<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="search">
        <a-row :gutter="24">
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="预出库单号">
              <a-input placeholder="请输入预出库单号" v-model="queryParams.orderNo"></a-input>
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="出库人">
              <a-input placeholder="请输入出库人" v-model="queryParams.stockOutUser"></a-input>
            </a-form-item>
          </a-col>
          <template v-if="toggleSearchStatus">
            <a-col :xl="6" :lg="7" :md="8" :sm="24">
              <a-form-item label="状态">
                <!--                <a-input placeholder="请输入状态（-1待出库，0已出库，1删除 ）" v-model="queryParam.state"></a-input>-->
                <a-select v-model="queryParams.state" placeholder="请选择状态">
                  <a-select-option v-for="(d,i) in stateList" :key="d.id" :value="d.id">{{ d.value }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :xl="6" :lg="7" :md="8" :sm="24">
              <a-form-item label="出库日期">
                <a-range-picker :style="{width: '100%'}" format="YYYY-MM-DD"
                                :placeholder="['开始时间', '结束时间']"
                                v-model="rangePikerDate"
                                @change="onQueryDateChange" />
              </a-form-item>
            </a-col>
          </template>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
              <a-button type="primary" @click="search" icon="search">查询</a-button>
              <a-button type="primary" @click="resetSearch" icon="reload" style="margin-left: 8px">重置</a-button>
              <a @click="handleToggleSearch" style="margin-left: 8px">
                {{ toggleSearchStatus ? '收起' : '展开' }}
                <a-icon :type="toggleSearchStatus ? 'up' : 'down'" />
              </a>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <!-- 查询区域-END -->

    <!-- 操作按钮区域 -->
    <div class="table-operator">
<!--      <a-button @click="addModalShow" type="primary" icon="plus">新增</a-button>-->
      <a-button type="primary" icon="download" :loading="exportLoading" @click="handleExportXlsAll('预出库单主表')">导出Excel
      </a-button>

      <a-dropdown v-if="selectedRowKeys.length > 0">
        <a-menu slot="overlay">
          <a-menu-item key="1" @click="outOrderBatchDelete(selectedRowKeys)">
            <a-icon type="delete" />
            删除
          </a-menu-item>
        </a-menu>
        <a-button style="margin-left: 8px"> 批量操作
          <a-icon type="down" />
        </a-button>
      </a-dropdown>
    </div>

    <!-- table区域-begin -->
    <div>
      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">
        <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择 <a
        style="font-weight: 600">{{ selectedRowKeys.length }}</a>项
        <a style="margin-left: 24px" @click="onClearSelected">清空</a>
      </div>

      <a-table
        ref="table"
        size="middle"
        bordered
        rowKey="id"
        class="j-table-force-nowrap"
        :columns="columns"
        :dataSource="outOrderDataSource"
        :pagination="mainPagination"
        :loading="loading"
        :scroll="{ x: true }"
        :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
        @change="mainPaginationChange">

          <span slot='state' slot-scope='text, record'>
          <a-tag class='rcicon-tag' v-if='record.state==-1'>草稿</a-tag>
          <a-tag class='ant-tag-blue' v-else-if='record.state==0'>审批中</a-tag>
          <a-tag class='ant-tag-green' v-else-if='record.state==1'>已出库</a-tag>
          <a-tag class='ant-tag-red' v-else-if='record.state==-2'>已删除</a-tag>
        </span>

        <template slot="htmlSlot" slot-scope="text">
          <div v-html="text"></div>
        </template>
        <template slot="imgSlot" slot-scope="text">
          <span v-if="!text" style="font-size: 12px;font-style: italic;">无图片</span>
          <img v-else :src="getImgView(text)" height="25px" alt=""
               style="max-width:80px;font-size: 12px;font-style: italic;" />
        </template>
        <template slot="fileSlot" slot-scope="text">
          <span v-if="!text" style="font-size: 12px;font-style: italic;">无文件</span>
          <a-button
            v-else
            :ghost="true"
            type="primary"
            icon="download"
            size="small"
            @click="uploadFile(text)">
            下载
          </a-button>
        </template>

        <span slot="action" slot-scope="text, record">
<!--          <a v-if='record.state=="-1"' @click='editModalShow(record)'>编辑</a> -->

          <a-button v-has='"outPre:pipMangeSure"' v-if='record.state=="0" && (record.baseMange) &&  !(record.pipMange)&& !(record.storeSure) ' type="primary" @click="editModalShow(record)">运管备案</a-button>
          <a-button  v-has='"outPre:pipMangeSureBack"' v-else-if='record.state=="0" && (record.baseMange) && (record.pipMange)&& !(record.storeSure) '  type="danger" @click="editModalShow(record)">撤销运管备案</a-button>
          <a v-else @click='editModalShow(record)'>详情</a>
          <a-button v-if='record.state=="1"' type="" @click="handleExportXlsList(record)">出/提货单</a-button>

<!--          <a-dropdown>
            <a v-if='record.state=="-1"' class="ant-dropdown-link">更多 <a-icon type="down" /></a>
            <a-menu slot="overlay">
              <a-menu-item>
                <a-popconfirm title="确定删除吗?" @confirm="() => outOrderDelete(record.id)">
                  <a>删除</a>
                </a-popconfirm>
              </a-menu-item>
            </a-menu>
          </a-dropdown>-->
        </span>

      </a-table>
    </div>

    <!--    <flowerOutorderPre-modal ref='modalForm' @ok='modalFormOk'></flowerOutorderPre-modal>-->
    <a-modal v-model:visible="addOrEditVisible" width="85%" :title="firstModalTitle"
             :maskClosable="false">
      <a-spin :spinning="firstModalSpinning" tip="数据保存中...">
        <div>
          <a-row>
            <a-col  :xl="8" :lg="8" :md="12" :sm="24">
              <div style="display: inline-block;">预出库单号：</div>
              <div style="display: inline-block;width: 70%">
                <a-input v-model="outOrder.orderNo" placeholder="自动生成" disabled />
              </div>
            </a-col>
            <a-col  :xl="8" :lg="8" :md="12" :sm="24">
              <div style="display: inline-block;color: red;">*</div>
              <div style="display: inline-block">渠道：</div>
              <div style="display: inline-block;">
                <a-select v-model="outOrder.channel" placeholder="请选择渠道" style="width: 130px;" @change="channelChange">
                  <a-select-option v-for="(d,i) in channelList" :key="d.id" :value="d.channel">{{ d.channel }}
                  </a-select-option>
                </a-select>
              </div>
            </a-col>
            <a-col  :xl="8" :lg="8" :md="12" :sm="24" v-show="accountnoShow">
              <div style="display: inline-block;color: red;">*</div>
              <div style="display: inline-block">账号：</div>
              <div style="display: inline-block;">
                <a-select v-model="outOrder.accountno" placeholder="请选择账号" style="width: 130px;">
                  <a-select-option v-for="(d,i) in accountnoList" :key="d.id" :value="d.account">{{ d.account }}
                  </a-select-option>
                </a-select>
              </div>
            </a-col>

            <a-col  :xl="8" :lg="8" :md="12" :sm="24">
              <div style="display: inline-block;color: red;">*</div>
              <div style="display: inline-block">出库人：</div>
              <div style="display: inline-block;width: 70%">
                <a-input v-model="outOrder.stockOutUser" placeholder="请输入出库人" />
              </div>
            </a-col>
            <a-col  :xl="8" :lg="8" :md="12" :sm="24">
              <div style="display: inline-block">出库时间：</div>
              <div style="display: inline-block;width: 70%">
                <!--     禁用以前时间  :disabled-date='disabledDate'-->
                <a-date-picker v-model:value="outOrder.stockInTime"
                               :default-value="moment(defaultStockInTime, dateFormat)" :valueFormat="dateFormat"
                               :disabled-date="disabledDate"
                               placeholder="请选择出库时间" />
              </div>
            </a-col>
            <a-col :xl='8' :lg='8' :md='12' :sm='24'>
              <div style='display: inline-block;color: red;'>*</div>
              <div style='display: inline-block'>客户：</div>
              <div style='display: inline-block;width: 80%'>
                <a-input v-model='outOrder.user' disabled />
              </div>
            </a-col>
            <a-col  :xl="8" :lg="8" :md="12" :sm="24">
              <div style="display: inline-block;color: red;">*</div>
              <div style="display: inline-block">电话：</div>
              <div style="display: inline-block;width: 70%">
                <a-input v-model="outOrder.phone" placeholder="请输入电话" />
              </div>
            </a-col>

            <a-col :xl='8' :lg='8' :md='12' :sm='24'>
              <div style='display: inline-block;color: red;'>*</div>
              <div style='display: inline-block'>交货方式：</div>
              <div style='display: inline-block;width: 80%'>
                <j-dict-select-tag style='display: inline-block;width: 80%' v-model='outOrder.toType' dict-code='ch_toType'></j-dict-select-tag>
                <!--                <a-input v-model='outOrder.toType' placeholder='请输入交货方式' />-->
              </div>
            </a-col>
            <a-col :xl='8' :lg='8' :md='12' :sm='24'>
              <div style='display: inline-block;color: red;'>*</div>
              <div style='display: inline-block'>车号/联系方式：</div>
              <div style='display: inline-block;width: 50%'>
                <a-input v-model='outOrder.carno' placeholder='请输入车号/联系方式' />
              </div>
            </a-col>
            <a-col  :xl="16" :lg="16" :md="16" :sm="24">
              <div style="display: inline-block;color: red;">*</div>
              <div style="display: inline-block">地址：</div>
              <div style="display: inline-block;width: 70%">
                <a-input v-model="outOrder.address" placeholder="请输入地址" />
              </div>
            </a-col>
            <a-col  :xl="8" :lg="8" :md="12" :sm="24" >
              <div style="display: inline-block;color: red;">*</div>
              <div style="display: inline-block;">账期：</div>
              <div style="display: inline-block;">
                <a-radio-group v-model="outOrder.period" @change="periodChange">
                  <a-radio v-for="(item,index)  in periodList" :key="index" :value="item">{{ item }}</a-radio>
                </a-radio-group>
              </div>
            </a-col>

            <a-col :xl='8' :lg='8' :md='12' :sm='24'>
              <div style='display: inline-block;color: red;'>*</div>
              <div style='display: inline-block;'>总数量：</div>
              <div style='display: inline-block;width: 80%;'>
                <a-input v-model='outOrder.totalnumber' disabled placeholder='自动' />
              </div>
            </a-col>
            <a-col :xl='8' :lg='8' :md='12' :sm='24'>
              <div style='display: inline-block;color: red;'>*</div>
              <div style='display: inline-block;'>总金额：</div>
              <div style='display: inline-block;width: 80%;'>
                <a-input v-model='outOrder.totalprice' disabled placeholder='自动' />
              </div>
            </a-col>
            <a-col :xl='24' :lg='24' :md='24' :sm='24'>
              <div style='display: inline-block;'>备注：</div>
              <div style='display: inline-block;width: 80%;'>
                <a-textarea v-model='outOrder.remarks' placeholder='请输入备注'></a-textarea>
              </div>
            </a-col>
          </a-row>
        </div>
        <a-divider />
        <div style="margin-top: -20px">
          <div style="font-size: 20px;color: #0742f3;margin-bottom: 3px">出库商品</div>
<!--          <a-button type="primary" icon="plus" @click="varietyModalShow">新增</a-button>-->
          <div style="margin-top: 7px">
            <a-table :columns="varietyColumns" :data-source="varietyDataSource"
                     bordered row-key="uuid"
                     :loading="varietyLoading"
                     :scroll="{ y: 300 }">
<!--              <template v-for="colNumber2 in ['number']" :slot="colNumber2" slot-scope="text, record, index"
                        style="width: 100%;">
                <div :key="colNumber2" style="text-align: center;margin-right: 0;width: 100%;">
                  <input v-model:value="record.number" style="width: 100%;text-align: center;" placeholder="请输入数量" />
                </div>
              </template>-->
<!--              <template slot="operation" slot-scope="text, record">
                <a-popconfirm v-if="varietyDataSource.length" title="确定删除?"
                              @confirm="() => varietyDelete(record.uuid)">
                  <a>删除</a>
                </a-popconfirm>
              </template>-->
            </a-table>
          </div>
        </div>
      </a-spin>
      <template slot="footer">
<!--        <a style="color: red!important;"> 请先点【保存】，再点【确认出库】</a>-->
        <a-button key="back" style='margin-right: 10px' :loading="sureOutLoading" @click="addOrEditVisible=false">
          关闭
        </a-button>
        <a-button v-has='"outPre:pipMangeSure"'  v-if='outOrder.state=="0"  && (outOrder.baseMange) &&  !(outOrder.pipMange)&& !(outOrder.storeSure)' style='margin-right: 10px' key="submit" type="primary" :loading="sureOutLoading"
                  @click="prePipMange(outOrder)">
          运管备案
        </a-button>
<!--
        <a-button key="submit" type="primary" :loading="sureOutLoading" @click="outOrderAddOrEdit">
          保存
        </a-button>-->
        <a-button  v-has='"outPre:pipMangeSureBack"'  v-if='outOrder.state=="0" && (outOrder.baseMange) && (outOrder.pipMange)&& !(outOrder.storeSure) ' key="submit" type="danger" :loading="sureOutLoading"
                  @click="prePipMangeBack(outOrder)">
          撤销运管备案
        </a-button>
      </template>
    </a-modal>
    <a-modal v-model:visible="varietyVisible" width="80%" title="商品选择" @ok="varietyAdd">
      <div style="margin-bottom: 10px">
        <a-row style="margin-top: 10px">
          <a-col :span="6">
            <div style="display: inline-block;width: 45px;">产品：</div>
            <div style="display: inline-block;width: 70%">
              <a-input v-model="queryVarietyParams.variety" placeholder="请输入产品名称" allow-clear
                       @change="searchFlowerVarietys" />
            </div>
          </a-col>
          <a-col  :xl="8" :lg="8" :md="12" :sm="24">
            <div style="display: inline-block;width: 80px;">商品编码：</div>
            <div style="display: inline-block;width: 65%">
              <a-input v-model="queryVarietyParams.varietyCode" placeholder="请输入商品编码" allow-clear
                       @change="searchFlowerVarietys" />
            </div>
          </a-col>
          <a-col :span="7">
            <div style="display: inline-block;width: 45px;">冷库：</div>
            <div style="display: inline-block;width: 70%">
              <a-select v-model="queryVarietyParams.storehouse" style="width: 100%;" placeholder="请选择冷库"
                        @change="searchFlowerVarietys">
                <a-select-option v-for="d in hoseList" :key="d.id" :value="d.code">{{ d.name }}</a-select-option>
              </a-select>
            </div>
          </a-col>
          <a-col :span="3">
            <a-button type="primary" icon="search" @click="searchFlowerVarietys">
              查询
            </a-button>
          </a-col>
        </a-row>
      </div>
      <a-table :columns="selectVarietyColumns" :data-source="selectVarietyDataSource" bordered
               :loading="selectVarietyLoading"
               :row-selection="{selectedRowKeys: selectedRowKeys,type: 'checkbox',onChange:onVarietySelectChange,onSelect:varietyOnSelect,
               onSelectAll:varietyOnSelectAll}"
               row-key="varietyNumber"
               :scroll="{y:280}"
               :pagination="varietyPagination"
               @change="varietyPaginationChange"
      ></a-table>
    </a-modal>
  </a-card>
</template>

<script>

import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import FlowerOutorderPreModal from './modules/FlowerOutorderPreModal'
import '@/assets/less/TableExpand.less'
import { ifInteger } from '../../utils/ifNumber'
import { getTodayDate, getCurrentYearAndMonth } from '@/utils/getDate'
import moment from 'moment'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import { downFile } from '@/api/manage'
import {
  getFlowerVarietys,
  getFlowerPreOutorder,
  getFlowerOutorderPreinfoByMainId,
  flowerOutorderPreAdd,
  flowerOutorderPreEdit,
  flowerOutorderPreDeleteBatch,
  preSreoutOrder,preSureoutOrderBack,baseMangeSure,baseMangeSureBack,pipMange,pipMangeBack,
  flowerOutOrderPreDelete,  getFlowerChannel, getFlowerAccountByMainId,
  period
} from '../../api/vegetableAPI'
import { getUuid } from '../../utils/uuid'
import Vue from 'vue'
import store from '@/store'

export default {
  name: 'FlowerOutorderPreList',
  mixins: [JeecgListMixin],
  components: {
    FlowerOutorderPreModal
  },
  data() {
    return {
      queryParams: {// 主页查询
        orderNo: '',
        stockOutUser: '',
        state: '',
        sDate: '',//开始时间
        eDate: ''//结束时间
      },
      rangePikerDate: [],
      // sourceBaseList: [],//基地列表
      // sourceGreenhouseList: [],//地块列表
      queryVarietyParams: {// 商品选择弹窗的查询
        variety: '',
        varietyCode: '',
        storehouse: ''
      },
      stateList: [{ id: '', value: '全部' }, { id: -1, value: '待出库' }, { id: 0, value: '已出库' }, { id: -2, value: '已删除' } ],//-1待出库，0已出库，1删除
      description: '预出库单主表管理页面',
      // 表头
      columns: [
        {
          title: '#',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: 'center',
          customRender: function(t, r, index) {
            return parseInt(index) + 1
          }
        },
        {
          title: '状态',
          align: 'center',
          dataIndex: 'state',
          scopedSlots: { customRender: 'state' },

        },
        {
          title: '预出库单号',
          align: 'center',
          dataIndex: 'orderNo',
          width: 140,
          ellipsis: true
        }, {
          title: '账期',
          align: 'center',
          width: 100,
          dataIndex: 'period'
        },
        {
          title: '出库人',
          align: 'center',
          dataIndex: 'stockOutUser',
          ellipsis: true,
          width: 100
        }, {
          title: '电话',
          align: 'center',
          dataIndex: 'phone',
          ellipsis: true,
          width: 100
        },
        {
          title: '出库时间',
          align: 'center',
          dataIndex: 'stockInTime',
          customRender: function(text) {
            return !text ? '' : (text.length > 10 ? text.substr(0, 10) : text)
          },
          width: 130,
          ellipsis: true
        },
        {
          title: '渠道',
          align: 'center',
          dataIndex: 'channel',
          ellipsis: true,
          width: 80
        },
        {
          title: '账号',
          align: 'center',
          dataIndex: 'accountno',
          ellipsis: true,
          width: 100
        },
        {
          title: '地址',
          align: 'center',
          dataIndex: 'address',
          ellipsis: true,
          width: 150
        },

        {
          title: '地基管理员',
          align: 'center',
          dataIndex: 'baseMange',
          ellipsis: true,

        },{
          title: '地基管理员时间',
          align: 'center',
          dataIndex: 'baseMangeTime',
          ellipsis: true,
        },
        {
          title: '运管备案',
          align: 'center',
          dataIndex: 'pipMange',
          ellipsis: true,

        }, {
          title: '运管备案',
          align: 'center',
          dataIndex: 'pipMangeTime',
          ellipsis: true,
        },{
          title: '库管确认',
          align: 'center',
          dataIndex: 'storeSure',
          ellipsis: true,
        },{
          title: '库管确认',
          align: 'center',
          dataIndex: 'storeSureTime',
          ellipsis: true,
        },
        {
          title: '备注',
          align: 'center',
          dataIndex: 'remarks',
          ellipsis: true,
          width: 150
        },
        {
          title: '创建日期',
          align: 'center',
          dataIndex: 'createTime',
          customRender: function(text) {
            return !text ? '' : (text.length > 10 ? text.substr(0, 10) : text)
          },
          ellipsis: true,
          width: 100
        },

        {
          title: '创建人',
          align: 'center',
          dataIndex: 'createBy_dictText',
          ellipsis: true,
          width: 100
        },

        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          fixed: 'right',
          width: 200,
          scopedSlots: { customRender: 'action' }
        }
      ],
      url: {
        list: '/flower/flowerOutorderPre/list',
        delete: '/flower/flowerOutorderPre/delete',
        deleteBatch: '/flower/flowerOutorderPre/deleteBatch',
        // exportXlsUrl: '/flower/flowerOutorderPre/exportXls',
        exportXlsUrl: '/flower/flowerOutorderPre/exportXlsAll',
        importExcelUrl: 'flower/flowerOutorderPre/importExcel'
      },
      dictOptions: {},
      outOrderDataSource: [],
      firstModalTitle: '',
      addOrEditFlag: 'add',//打开的弹窗是新增还是编辑的标识
      varietyLoading: false,//是否显示第一个弹窗中表格的加载状态
      firstModalSpinning: false,//第一个弹窗是否处于加载中
      selectVarietyLoading: true,//是否显示第二个弹窗中表格的加载状态
      addOrEditVisible: false,//是否打开新增或编辑的弹窗
      varietyVisible: false,//是否打开商品选择的弹窗
      outOrder: {
        sourceBase: '',//基地
        sourceGreenhouse: '',//地块
        orderNo: '',
        period: '',//账期
        phone: '',
        address: '',
        stockOutUser: '',
        carPhone: '',
        storehouse: '',
        stockInTime: '',
        remarks: '',
        channel: '',//渠道
        accountno: ''//账号
      },
      channelList: [],
      accountnoList: [],
      accountnoShow: false,//第一个弹窗中是否显示账号的选择框
      defaultStockInTime: '',
      dateFormat: 'YYYY-MM-DD',
      varietyColumns: [// 第一个弹窗的表头
        {
          title:'基地',
          align:"center",
          dataIndex: 'sourceBase_dictText',
          // width: 120,
        },{
          title:'大棚',
          align:"center",
          dataIndex: 'sourceGreenhouse_dictText',
          // width: 100,
        },{
          title: '冷库',
          dataIndex: 'storehouse_dictText',
          align: 'center',
          // width: 100
        }, {
          title: '成本中心',
          dataIndex: 'cost_dictText',
          align: 'center',
          // width: 120
        },
        {
          title: '批次',
          align: 'center',
          dataIndex: 'productionId'
          // width: 120,
        }, {
          title: '产品',
          dataIndex: 'variety',
          align: 'center'
        }, {
          title: '商品编码',
          dataIndex: 'varietyCode',
          align: 'center'
        }, {
          title: '规格',
          dataIndex: 'packingSpecifications',
          align: 'center'
        }, {
          title: '单位',
          dataIndex: 'flowerPoleLength',
          align: 'center',
          width: 65,
        }, {
          title: '等级',
          dataIndex: 'classes',
          align: 'center',
          width: 65,
        }, {
          title: '数量',
          dataIndex: 'number',
          align: 'center',
        },{
          title: '单价',
          dataIndex: 'price',
          align: 'center',
        }, {
          title: '总价',
          dataIndex: 'totalprice',
          align: 'center',
        },
        {
          title: '操作',
          dataIndex: 'operation',
          align: 'center',
          width: 70,
          scopedSlots: { customRender: 'operation' }
        }
      ],
      hoseList: [], //冷库列表
      selectVarietyColumns: [// 第二个弹窗的表头
        {
          title:'基地',
          align:"center",
          dataIndex: 'sourceBase_dictText',
          width: 120,
        },{
          title:'大棚',
          align:"center",
          dataIndex: 'sourceGreenhouse_dictText',
          width: 100,
        },{
          title: '冷库',
          dataIndex: 'storehouse_dictText',
          align: 'center'
        }, {
          title: '产品',
          dataIndex: 'variety',
          align: 'center'
        }, {
          title: '商品编码',
          dataIndex: 'varietyCode',
          align: 'center'
        }, {
          title: '规格',
          dataIndex: 'packingSpecifications',
          align: 'center'
        }, {
          title: '单位',
          dataIndex: 'flowerPoleLength',
          align: 'center'
        }, {
          title: '库存',
          dataIndex: 'tagNum',
          align: 'center'
        }
      ],
      varietyNumber: 1,
      varietyDataSource: [],// 第一个弹窗中的商品列表
      selectVarietyDataSource: [],// 第二个弹窗中可选择的商品列表
      selectVariety: [],// 第二个弹窗中已选择的商品
      mainPagination: {// 主页表格的分页
        total: 0,
        current: 1,
        pageSize: 10,//每页中显示10条数据
        showSizeChanger: true,
        pageSizeOptions: ['10', '20', '50', '100'],//每页中显示的数据
        showTotal: total => `共有 ${total} 条数据`  //分页中显示总的数据
      },
      varietyPagination: {// 商品选择弹窗中表格的分页
        total: 0,
        current: 1,
        pageSize: 10,//每页中显示10条数据
        showSizeChanger: false,
        showQuickJumper: true,
        showTotal: total => `共有 ${total} 条数据`  //分页中显示总的数据
      },
      firstModalLoading: false,//第一个弹窗保存按钮是否处于加载中
      periodList: [],//从后台取回的账期列表
      exportLoading: false,
      sureOutLoading: false
    }
  },
  computed: {
    importExcelUrl: function() {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`
    }
  },
  created() {
    //获取冷库列表
    this.hoseList = JSON.parse(localStorage.getItem('ch_storehouse') ? localStorage.getItem('ch_storehouse') : '')
    this.getChannel()
    this.getPeriod()
  },
  mounted() {
    this.queryFlowerOutorder()
  },
  methods: {
    moment,
    search() {// 主页中根据条件查询
      this.mainPagination.current = 1
      this.queryFlowerOutorder()
    },
    onQueryDateChange(date, dateString) {// 日期段选择改变时的回调
      this.queryParams.sDate = dateString[0]
      this.queryParams.eDate = dateString[1]
    },
    resetSearch() {// 重置查询
      this.queryParams = {
        orderNo: '',
        stockOutUser: '',
        state: '',
        sDate: '',//开始时间
        eDate: ''//结束时间
      }
      this.rangePikerDate = []
      this.search()
    },
    todayDate() {// 设置新增弹窗中的出库时间的默认值为当前日期
      this.defaultStockInTime = getTodayDate()
      this.outOrder.stockInTime = getTodayDate()
    },
    searchFlowerVarietys() {//根据条件查询商品选择弹窗中的商品列表
      this.varietyPagination.current = 1
      this.queryFlowerVarietys()
    },
    mainPaginationChange(pagination) {
      this.mainPagination.current = pagination.current
      this.mainPagination.pageSize = pagination.pageSize
      this.queryFlowerOutorder()
    },
    varietyPaginationChange(pagination) {
      this.varietyPagination = pagination
      this.queryFlowerVarietys()
    },
    queryFlowerOutorder() {// 获取出库单
      this.loading = true
      this.outOrderDataSource.length = 0
      let params = {
        pageNo: this.mainPagination.current,
        pageSize: this.mainPagination.pageSize
      }
      params = { ...this.queryParams, ...params }
      getFlowerPreOutorder(params).then(res => {
        if (res.success) {
          this.mainPagination.total = res.result.total
          this.outOrderDataSource = res.result.records
        } else {
          this.$message.error(res.message)
        }
        this.loading = false
      })
    },
    addModalShow() {//打开第一个弹窗(新增)
      this.addOrEditFlag = 'add'
      this.firstModalTitle = '新增'
      let realname = store.getters.userInfo.realname
      let phone = store.getters.userInfo.phone

      this.outOrder = {
        orderNo: '',
        period: this.periodList.length === 1 ? this.periodList[0] : this.periodList[1],//账期
        address: '',
        stockOutUser: realname,
        phone: phone,
        storehouse: '',
        stockInTime: '',
        remarks: '',
        channel: '',//渠道
        accountno: '',//账号
        state: '-1'//
      }
      this.varietyDataSource = []
      this.todayDate()
      this.getPeriod()
      this.firstModalLoading = false
      this.addOrEditVisible = !this.addOrEditVisible
    },
    editModalShow(record) {//打开第一个弹窗(编辑)
      // this.outOrder={}
      this.addOrEditFlag = 'edit'
      this.firstModalTitle = '编辑'
      this.outOrder = record
      if (this.outOrder.accountno !== '') {//打开编辑界面时如果账号有数据的话，要把账号显示出来
        this.accountnoShow = true
      }
      this.varietyDataSource.length = 0
      this.queryFlowerOutorderinfo(record.id)
      this.setPeriod()
      this.firstModalLoading = false
      this.addOrEditVisible = !this.addOrEditVisible
    },
    varietyModalShow() {//打开第二个弹窗
      /*设置下面这两行是为了处理再次打开商品选择弹窗时，
      还会在界面上保留上次选择商品而实际上没有选择任何商品的问题*/
      this.selectedRowKeys.length = 0
      this.selectionRows.length = 0

      this.selectVariety = []
      this.varietyPagination = {// 商品选择弹窗中表格的分页
        total: 0,
        current: 1,
        pageSize: 10,//每页中显示10条数据
        showSizeChanger: false,
        showQuickJumper: true,
        showTotal: total => `共有 ${total} 条数据`  //分页中显示总的数据
      }
      this.queryVarietyParams = {// 商品选择弹窗的查询
        sourceBase: '',//基地
        sourceGreenhouse : '',//地块
        variety: '',
        varietyCode: '',
        storehouse: ''
      }
      this.varietyNumber = 1
      this.queryFlowerVarietys()
      this.varietyVisible = !this.varietyVisible
    },
    queryFlowerOutorderinfo(id) {//获取第一个弹窗的商品数据
      this.varietyLoading = true
      let params = {// 因为第一个弹窗中的表格会有新增商品的数据，因此无法使用分页，故将pageSize设大一些
        id: id,
        pageNo: 1,
        pageSize: 1000
      }
      getFlowerOutorderPreinfoByMainId(params).then(res => {
        if (res.success) {
          let records = res.result.records
          this.varietyDataSource = records
          this.varietyDataSource.map(item => {// 将uuid封装进varietyDataSource中的各用户对象中,为table中的key使用
            item.uuid = getUuid()
          })
        } else {
          this.$message.error(res.message)
        }
        this.varietyLoading = false
      })
    },
    queryFlowerVarietys() {// 获取第二个弹窗中的商品列表
      this.selectVarietyLoading = true
      let params = {
        pageNo: this.varietyPagination.current,
        pageSize: this.varietyPagination.pageSize
      }
      params = { ...this.queryVarietyParams, ...params }
      getFlowerVarietys(params).then(res => {
        if (res.success) {
          this.varietyPagination.total = res.result.total
          this.selectVarietyDataSource = res.result.records

          // 将uuid封装进selectVarietyDataSource中的各用户对象中,为table中的key使用
          this.selectVarietyDataSource.map(item => {
            item.uuid = getUuid()
            delete item.id
          })
          // 将varietyNumber封装进selectVarietyDataSource中的各用户对象中,为商品选择弹窗中table的key使用
          if (this.varietyPagination.current > 1) {
            this.varietyNumber = (this.varietyPagination.current - 1) * 10 + 1
          } else {
            this.varietyNumber = 1
          }
          for (let item of this.selectVarietyDataSource) {
            item.varietyNumber = this.varietyNumber
            this.varietyNumber += 1
          }
        } else {
          this.$message.error(res.message)
        }
        this.selectVarietyLoading = false
      })
    },
    onVarietySelectChange(selectedRowKeys, selectionRows) {
      this.selectedRowKeys = selectedRowKeys// 如果不加这两行的话无法单选
      this.selectionRows = selectionRows
    },
    varietyOnSelect(record, selected, selectedRows) {//选择/取消选择某个商品的回调
      if (selected) {//如果是选择某个商品的操作，就将所选择的商品添加进selectVariety
        this.selectVariety.push(record)
      } else {//如果是取消选择某个商品的操作，则从selectVariety中删除相应的商品
        this.selectVariety = this.selectVariety.filter(item => item.varietyNumber !== record.varietyNumber)
      }
    },
    varietyOnSelectAll(selected, selectedRows, changeRows) {//选择/取消选择所有商品的回调
      if (selected) {//如果是选择所有商品的操作，就将所选择的商品添加进selectVariety
        this.selectVariety = [...this.selectVariety, ...changeRows]
      } else {//如果是取消选择所有商品的操作，则从selectVariety中删除相应的商品
        for (let i of changeRows) {
          this.selectVariety = this.selectVariety.filter(item => item.varietyNumber !== i.varietyNumber)
        }
      }
    },
    varietyAdd() {// 第二个弹窗中的新增商品
      /*if (JSON.stringify(this.selectVariety) !== '{}') {//判断this.selectVariety是否为空
        this.selectVariety.number = ''// 为selectVariety对象中添加number元素
        this.selectVariety.totalprice = ''// 为selectVariety对象中添加totalprice元素

        /!*let varietyCodeFlag = false//第一个弹窗表格中的商品是否包含新添加的商品
        for (let item of this.varietyDataSource) {
          if (item.varietyCode === this.selectVariety.varietyCode &&
            item.storehouse_dictText === this.selectVariety.storehouse_dictText) {
            this.$message.error(`该预出库单出库商品中已有冷库为${item.storehouse_dictText}，商品编号为:${item.varietyCode}的商品`)
            varietyCodeFlag = true
            return
          }
        }
        if (!varietyCodeFlag) {
          this.varietyDataSource.push(this.selectVariety)
        }*!/
        this.varietyDataSource.push(this.selectVariety)
      }*/
      this.selectVariety.map(item => {

        item.number = ''
        item.totalprice = ''
      })
      for (let item of this.selectVariety) {
        this.varietyDataSource.push(item)
      }
      this.varietyVisible = !this.varietyVisible
    },
    varietyDelete(id) {// 第一个弹窗中删除商品
      const dataSource = [...this.varietyDataSource]
      this.varietyDataSource = dataSource.filter(item => item.uuid !== id)
    },
    outOrderAddOrEdit() {// 确定新增或编辑出库单
      let allNumberFlag = true//是否所有的商品都有数量的标识
      if (this.outOrder.channel === '') {
        this.$message.error('请选择渠道')
      } else if (this.accountnoShow && this.outOrder.accountno === '') {
        this.$message.error('请选择账号')
      } else if (this.outOrder.period === '') {
        this.$message.error('请选择账期')
      } else if (this.outOrder.phone === '') {
        this.$message.error('请输入电话')
      } else if (this.outOrder.address === '') {
        this.$message.error('请输入地址')
      }
        // else if (this.outOrder.stockOutUser===''){
        //   this.$message.error('请输入出库人');
        // }else if (this.outOrder.stockInTime===''){
        //   this.$message.error('请选择出库时间');
      // }
      else {
        for (let item of this.varietyDataSource) {
          if (item.number === '' || item.number === null) {
            this.$message.error('请输入数量')
            allNumberFlag = false
            return
          }
          if (!ifInteger(item.number)) {
            this.$message.error('商品数量必须为正整数')
            return
          }
        }
        if (allNumberFlag) {
          this.outOrder.flowerOutorderPreinfoList = this.varietyDataSource// 将商品列表封装进outOrder中
          if (this.outOrder.flowerOutorderPreinfoList.length === 0) {
            this.$message.error('至少需要有一个出库商品')
          } else {
            this.sureOutLoading = true
            this.firstModalSpinning=true
            // 去掉varietyDataSource中每个对象（如果有）的uuid，此uuid是在前端生成的
            this.varietyDataSource.map(item => {
              delete item.uuid
            })
            if (this.addOrEditFlag === 'add') {// 新增出库单的情况
              flowerOutorderPreAdd(this.outOrder).then(res => {
                if (res.success) {
                  this.queryFlowerOutorder()
                  this.$message.success('新增预出库成功')
                  this.addOrEditVisible = false
                } else {
                  this.$message.error(res.message)
                }
                this.sureOutLoading = false
                this.firstModalSpinning=false
              })
            } else {// 编辑出库单的情况
              if (this.outOrder.flowerOutorderPreinfoList.length === 0) {
                this.$message.warning('至少需要一个出库商品')
              } else {
                flowerOutorderPreEdit(this.outOrder).then(res => {
                  if (res.success) {
                    this.queryFlowerOutorder()
                    this.$message.success('编辑预出库成功')
                    this.addOrEditVisible = false
                  } else {
                    this.$message.error(res.message)
                  }
                  this.sureOutLoading = false
                  this.firstModalSpinning=false
                })
                this.selectedRowKeys.length = 0//使新增或编辑后不显示批量删除的按钮
              }
            }
          }
        }
      }
    },
  /*  sureoutOrder(record) {
      this.sureOutLoading = true
      this.firstModalSpinning=true
      if(!record.id){
        this.$message.error("请先点【保存】按钮！")
        this.sureOutLoading = false
        this.firstModalSpinning=false
        return
      }
      let params = { id: record.id }
      preSreoutOrder(params).then(res => {
        if (res.success) {
          this.$message.success(res.message)
          this.queryFlowerOutorder()
          this.addOrEditVisible = false
        } else {
          this.$message.error(res.message)
        }
        this.sureOutLoading = false
        this.firstModalSpinning = false
      })
    },
    sureoutOrderBack(record) {
      this.sureOutLoading = true
      this.firstModalSpinning = true
      let params = { id: record.id }
      preSureoutOrderBack(params).then(res => {
        if (res.success) {
          this.$message.success(res.message)
          this.queryFlowerOutorder()
          this.addOrEditVisible = false
        } else {
          this.$message.error(res.message)
        }
        this.sureOutLoading = false
        this.firstModalSpinning = false
      })
    },*/
  /*  preBaseMangeSure(record) {
      this.sureOutLoading = true
      this.firstModalSpinning=true
      if(!record.id){
        this.$message.error("请先点【保存】按钮！")
        this.sureOutLoading = false
        this.firstModalSpinning=false
        return
      }
      let params = { id: record.id }
      baseMangeSure(params).then(res => {
        if (res.success) {
          this.$message.success(res.message)
          this.queryFlowerOutorder()
          this.addOrEditVisible = false
        } else {
          this.$message.error(res.message)
        }
        this.sureOutLoading = false
        this.firstModalSpinning = false
      })
    },
    preBaseMangeSureBack(record) {
      this.sureOutLoading = true
      this.firstModalSpinning = true
      let params = { id: record.id }
      baseMangeSureBack(params).then(res => {
        if (res.success) {
          this.$message.success(res.message)
          this.queryFlowerOutorder()
          this.addOrEditVisible = false
        } else {
          this.$message.error(res.message)
        }
        this.sureOutLoading = false
        this.firstModalSpinning = false
      })
    },*/
    prePipMange(record) {
      this.sureOutLoading = true
      this.firstModalSpinning=true
      if(!record.id){
        this.$message.error("请先点【保存】按钮！")
        this.sureOutLoading = false
        this.firstModalSpinning=false
        return
      }
      let params = { id: record.id }
      pipMange(params).then(res => {
        if (res.success) {
          this.$message.success(res.message)
          this.queryFlowerOutorder()
          this.addOrEditVisible = false
        } else {
          this.$message.error(res.message)
        }
        this.sureOutLoading = false
        this.firstModalSpinning = false
      })
    },
    prePipMangeBack(record) {
      this.sureOutLoading = true
      this.firstModalSpinning = true
      let params = { id: record.id }
      pipMangeBack(params).then(res => {
        if (res.success) {
          this.$message.success(res.message)
          this.queryFlowerOutorder()
          this.addOrEditVisible = false
        } else {
          this.$message.error(res.message)
        }
        this.sureOutLoading = false
        this.firstModalSpinning = false
      })
    },
    outOrderDelete(id) {
      flowerOutOrderPreDelete({ id: id }).then(res => {
        if (res.success) {
          this.queryFlowerOutorder()
          this.$message.success('删除成功')
        } else {
          this.$message.error(res.message)
        }
      })
    },
    outOrderBatchDelete(selectedRowKeys) {
      if (selectedRowKeys.length > 0) {
        let ids = ''
        for (let item of selectedRowKeys) {
          ids = ids + item + ','
        }
        flowerOutorderPreDeleteBatch({ ids: ids }).then(res => {
          if (res.success) {
            this.queryFlowerOutorder()
            this.selectedRowKeys.length = 0
            this.$message.success('批量删除成功')
          } else {
            this.$message.error(res.message)
          }
        })
      }
    },
    handleExportXlsList(record) {

      // 预览地址:  http://8.142.134.151:9998/jmreport/shareView/750516894332784640

      const token = Vue.ls.get(ACCESS_TOKEN)
      let url = window._CONFIG['jimuURL'] + '/jmreport/shareView/750516894332784640?id=' + record.id + '&token=' + token
      // let url =  "http://scht.ythxdny.com:9998/jmreport/shareView/750516894332784640?id="+record.id+"&token="+token
      window.open(url)

      /*
      let dt = new Date()
      let fileName = '出库单' + record.orderNo + dt.getFullYear() + '-' + (dt.getMonth() + 1) + '-' + dt.getDate()
      let param = this.getQueryParams()
      if (this.selectedRowKeys && this.selectedRowKeys.length > 0) {
        param['selections'] = this.selectedRowKeys.join(',')
      }
      // console.log('导出参数', param)
      let urlss = '/flower/flowerOutorderPre/exportXlsForOut'
      downFile(urlss, { id: record.id }).then((data) => {
        if (!data) {
          this.$message.warning('文件下载失败')
          return
        }
        if (typeof window.navigator.msSaveBlob !== 'undefined') {
          window.navigator.msSaveBlob(new Blob([data], { type: 'application/vnd.ms-excel' }), fileName + '.xlsx')
        } else {
          let url = window.URL.createObjectURL(new Blob([data], { type: 'application/vnd.ms-excel' }))
          let link = document.createElement('a')
          link.style.display = 'none'
          link.href = url
          link.setAttribute('download', fileName + '.xlsx')
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link) //下载完成移除元素
          window.URL.revokeObjectURL(url) //释放掉blob对象
        }
      })*/
    },
    //获取渠道
    getChannel() {
      getFlowerChannel().then(res => {
        if (res.success) {
          this.channelList = res.result.records
        } else {
          this.$message.error(res.message)
        }
      })
    },
    //渠道选择框的change
    channelChange(value, option) {
      this.accountnoList.length = 0
      this.outOrder.accountno = ''
      this.getAccountnoByMainId(option.key)
    },
    //根据渠道id获取账号
    getAccountnoByMainId(channelId) {
      let params = { id: channelId }
      getFlowerAccountByMainId(params).then(res => {
        if (res.success) {
          this.accountnoList = res.result
          if (this.accountnoList.length === 0) {
            this.accountnoShow = false
          } else {
            this.accountnoShow = true
          }
        } else {
          this.$message.error('未找到对应的账号')
        }
      })
    },
    // 日期选择框中不可选择的日期
    disabledDate(current) {
      return current < moment().subtract(1, 'day')//当前日期以前不可用
    },
    getPeriod() {//获取账期
      period().then(res => {
        this.periodList = res
      })
    },
    //账期单选的change
    periodChange(e) {
      this.outOrder.period = e.target.value
    },
    //设置账期（打开编辑弹窗时用）
    setPeriod() {
      period().then(res => {
        this.periodList = res
        if (this.periodList.length === 1) {//账期开关关闭时
          this.periodList.push(this.outOrder.period)
          this.periodList = Array.from(new Set(this.periodList))//去重
          this.periodList.sort()//升序排序
        }
      })
    },
    handleExportXlsAll(tital) {
      let fileName = tital
      let param = this.queryParams
      this.exportLoading = true
      if (this.selectedRowKeys && this.selectedRowKeys.length > 0) {
        param['selections'] = this.selectedRowKeys.join(',')
      }
      let urlss = this.url.exportXlsUrl
      downFile(urlss, param).then((data) => {
        if (!data) {
          this.$message.warning('文件下载失败')
          return
        }
        if (typeof window.navigator.msSaveBlob !== 'undefined') {
          window.navigator.msSaveBlob(new Blob([data], { type: 'application/vnd.ms-excel' }), fileName + '.xlsx')

          this.exportLoading = false
        } else {
          let url = window.URL.createObjectURL(new Blob([data], { type: 'application/vnd.ms-excel' }))
          let link = document.createElement('a')
          link.style.display = 'none'
          link.href = url
          link.setAttribute('download', fileName + '.xlsx')
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link) //下载完成移除元素
          window.URL.revokeObjectURL(url) //释放掉blob对象

          this.exportLoading = false
        }
      })
    },

  }
}
</script>
<style scoped>
@import '~@assets/less/common.less';
.ant-col {
  margin-top: 3px;
  height: 40px;
}
</style>